/*
 * ThreadSafeDataManager.cpp
 *
 *  Created on: 2014-1-7
 *      Author: root
 */

#include "ThreadSafeDataManager.h"

namespace miniGameServer {

miniGameServer::ThreadSafeDataManager& ThreadSafeDataManager::instance()
{
	static ThreadSafeDataManager _instance;
	return _instance;
}

ThreadSafeDataManager::ThreadSafeDataManager() {
	pthread_mutex_init(&readClientMutex,NULL);
	sem_init(&readListSem,0,0);

	pthread_mutex_init(&writeClientsMutex,NULL);
	sem_init(&writeListSem,0,0);
}

ThreadSafeDataManager::~ThreadSafeDataManager() {
	pthread_mutex_destroy(&readClientMutex);
	pthread_mutex_destroy(&writeClientsMutex);
	sem_destroy(&readListSem);
	sem_destroy(&writeListSem);
}

bool ThreadSafeDataManager::addOneReadClient(ClientClass *cc)
{
	pthread_mutex_lock(&readClientMutex);
	if(!cc->inReadQueue)
	{
		readClients.push(cc);
		cc->inReadQueue = true;
	}
	pthread_mutex_unlock(&readClientMutex);
	postReadSem();
	return true;
}

bool ThreadSafeDataManager::readListEmpty()
{
	return readClients.empty();
}

ClientClass * ThreadSafeDataManager::getOneReadClient()
{
	ClientClass *cc = NULL;
	pthread_mutex_lock(&readClientMutex);
	if(!readClients.empty())
	{
		cc = readClients.front();
		readClients.pop();
		cc->inReadQueue = false;
	}
	pthread_mutex_unlock(&readClientMutex);
	return cc;
}

void ThreadSafeDataManager::waitReadSem()
{
	sem_wait(&readListSem);
}

void ThreadSafeDataManager::postReadSem()
{
	sem_post(&readListSem);
}

bool ThreadSafeDataManager::addOneWriteclient(ClientClass*cc)
{
	pthread_mutex_lock(&writeClientsMutex);
	if(!cc->inWriteQueue)
	{
		writeClients.push(cc);
		cc->inWriteQueue = true;
	}
	pthread_mutex_unlock(&writeClientsMutex);
	postWriteSem();
	return true;
}
bool ThreadSafeDataManager::writeClientEmpty()
{
	return writeClients.empty();
}
ClientClass *ThreadSafeDataManager::getOneWriteClient()
{
	ClientClass *wcc = NULL;
	pthread_mutex_lock(&writeClientsMutex);
	if(!writeClients.empty())
	{
		wcc = writeClients.front();
		writeClients.pop();
		wcc->inWriteQueue = false;
	}
	pthread_mutex_unlock(&writeClientsMutex);
	return wcc;
}

void ThreadSafeDataManager::waitWriteSem()
{
	sem_wait(&writeListSem);
}

void ThreadSafeDataManager::postWriteSem()
{
	sem_post(&writeListSem);
}

}
